from flask import Blueprint, request, jsonify
from src.models.models import db, PracticeLog, Session, User, Word, Mistake
from datetime import datetime, timedelta
import json
from sqlalchemy import func, and_

analytics_bp = Blueprint('analytics', __name__)

@analytics_bp.route('/track-event', methods=['POST'])
def track_event():
    """埋点事件追踪"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        event_name = data.get('event_name')
        event_data = data.get('event_data', {})
        timestamp = data.get('timestamp', datetime.utcnow().isoformat())
        
        if not all([user_id, event_name]):
            return jsonify({'success': False, 'error': 'user_id and event_name are required'}), 400
        
        # 根据事件类型处理不同的埋点数据
        if event_name == 'word_view':
            # 单词查看事件
            word_id = event_data.get('word_id')
            if word_id:
                log = PracticeLog(
                    user_id=user_id,
                    word_id=word_id,
                    action='view',
                    timestamp=datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
                )
                db.session.add(log)
        
        elif event_name == 'audio_play':
            # 音频播放事件
            word_id = event_data.get('word_id')
            duration = event_data.get('duration', 0)
            if word_id:
                log = PracticeLog(
                    user_id=user_id,
                    word_id=word_id,
                    action='tts',
                    timestamp=datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
                )
                db.session.add(log)
        
        elif event_name == 'recording_submit':
            # 录音提交事件
            word_id = event_data.get('word_id')
            score = event_data.get('score')
            correct = event_data.get('correct')
            if word_id:
                log = PracticeLog(
                    user_id=user_id,
                    word_id=word_id,
                    action='record',
                    score=score,
                    correct=correct,
                    timestamp=datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
                )
                db.session.add(log)
        
        elif event_name == 'session_start':
            # 学习会话开始
            session = Session(
                user_id=user_id,
                date=datetime.fromisoformat(timestamp.replace('Z', '+00:00')).date(),
                plan_count=event_data.get('plan_count', 10)
            )
            db.session.add(session)
        
        elif event_name == 'session_end':
            # 学习会话结束
            duration = event_data.get('duration', 0)
            completed = event_data.get('completed', 0)
            
            # 更新最近的会话记录
            today = datetime.fromisoformat(timestamp.replace('Z', '+00:00')).date()
            session = Session.query.filter_by(
                user_id=user_id,
                date=today
            ).order_by(Session.created_at.desc()).first()
            
            if session:
                session.duration_sec = duration
                session.done_count = completed
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Event tracked successfully'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500

@analytics_bp.route('/user-stats/<int:user_id>', methods=['GET'])
def get_user_stats(user_id):
    """获取用户学习统计数据"""
    try:
        # 获取时间范围参数
        days = request.args.get('days', 7, type=int)
        end_date = datetime.utcnow().date()
        start_date = end_date - timedelta(days=days-1)
        
        # 基础统计
        total_words_learned = db.session.query(func.count(PracticeLog.word_id.distinct())).filter(
            PracticeLog.user_id == user_id,
            PracticeLog.action == 'view'
        ).scalar() or 0
        
        total_practice_time = db.session.query(func.sum(Session.duration_sec)).filter(
            Session.user_id == user_id,
            Session.date >= start_date
        ).scalar() or 0
        
        # 准确率统计
        correct_count = db.session.query(func.count(PracticeLog.id)).filter(
            PracticeLog.user_id == user_id,
            PracticeLog.action == 'record',
            PracticeLog.correct == True,
            PracticeLog.timestamp >= start_date
        ).scalar() or 0
        
        total_attempts = db.session.query(func.count(PracticeLog.id)).filter(
            PracticeLog.user_id == user_id,
            PracticeLog.action == 'record',
            PracticeLog.timestamp >= start_date
        ).scalar() or 0
        
        accuracy_rate = (correct_count / total_attempts * 100) if total_attempts > 0 else 0
        
        # 每日学习数据
        daily_stats = []
        for i in range(days):
            date = start_date + timedelta(days=i)
            
            # 当日学习单词数
            words_count = db.session.query(func.count(PracticeLog.word_id.distinct())).filter(
                PracticeLog.user_id == user_id,
                PracticeLog.action == 'view',
                func.date(PracticeLog.timestamp) == date
            ).scalar() or 0
            
            # 当日学习时长
            session_time = db.session.query(func.sum(Session.duration_sec)).filter(
                Session.user_id == user_id,
                Session.date == date
            ).scalar() or 0
            
            # 当日准确率
            day_correct = db.session.query(func.count(PracticeLog.id)).filter(
                PracticeLog.user_id == user_id,
                PracticeLog.action == 'record',
                PracticeLog.correct == True,
                func.date(PracticeLog.timestamp) == date
            ).scalar() or 0
            
            day_total = db.session.query(func.count(PracticeLog.id)).filter(
                PracticeLog.user_id == user_id,
                PracticeLog.action == 'record',
                func.date(PracticeLog.timestamp) == date
            ).scalar() or 0
            
            day_accuracy = (day_correct / day_total * 100) if day_total > 0 else 0
            
            daily_stats.append({
                'date': date.isoformat(),
                'words_learned': words_count,
                'study_time': session_time,
                'accuracy': round(day_accuracy, 1)
            })
        
        # 错词统计
        mistake_count = db.session.query(func.count(Mistake.id)).filter(
            Mistake.user_id == user_id
        ).scalar() or 0
        
        return jsonify({
            'success': True,
            'data': {
                'summary': {
                    'total_words_learned': total_words_learned,
                    'total_practice_time': total_practice_time,
                    'accuracy_rate': round(accuracy_rate, 1),
                    'mistake_count': mistake_count
                },
                'daily_stats': daily_stats,
                'period': {
                    'start_date': start_date.isoformat(),
                    'end_date': end_date.isoformat(),
                    'days': days
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@analytics_bp.route('/generate-weekly-report/<int:user_id>', methods=['POST'])
def generate_weekly_report(user_id):
    """生成周报"""
    try:
        data = request.get_json()
        week_index = data.get('week_index', 1)
        
        # 计算周报时间范围
        end_date = datetime.utcnow().date()
        start_date = end_date - timedelta(days=6)  # 最近7天
        
        # 获取用户统计数据
        stats_response = get_user_stats(user_id)
        if not stats_response.json['success']:
            return stats_response
        
        stats_data = stats_response.json['data']
        
        # 生成进度数据（用于图表）
        progress_data = []
        days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        
        for i, day_stat in enumerate(stats_data['daily_stats']):
            if i < len(days):
                progress_data.append({
                    'day': days[i],
                    'vocabulary': min(100, day_stat['words_learned'] * 10),  # 标准化到100
                    'accuracy': day_stat['accuracy']
                })
        
        # 获取Top5错词
        top_mistakes = db.session.query(Mistake, Word).join(Word).filter(
            Mistake.user_id == user_id
        ).order_by(Mistake.count.desc()).limit(5).all()
        
        mistake_words = [word.en for _, word in top_mistakes] if top_mistakes else [
            'example', 'difficult', 'pronunciation', 'vocabulary', 'grammar'
        ]
        
        # 生成KPI数据
        kpis = {
            'progress_data': progress_data,
            'top_mistakes': mistake_words,
            'total_words': stats_data['summary']['total_words_learned'],
            'accuracy_rate': stats_data['summary']['accuracy_rate'],
            'study_time': stats_data['summary']['total_practice_time'] // 60  # 转换为分钟
        }
        
        # 生成简单的表扬文案
        accuracy = stats_data['summary']['accuracy_rate']
        if accuracy >= 85:
            praise_text = f"Outstanding work! Your {accuracy}% accuracy shows exceptional dedication to learning English."
        elif accuracy >= 70:
            praise_text = f"Great job! Your {accuracy}% accuracy demonstrates solid understanding and steady progress."
        else:
            praise_text = f"Good effort! Your {accuracy}% accuracy shows you're learning. Keep practicing!"
        
        # 保存或更新周报
        from src.models.models import WeeklyReport
        
        report = WeeklyReport.query.filter_by(
            user_id=user_id,
            week_index=week_index
        ).first()
        
        if report:
            report.kpis_json = json.dumps(kpis)
            report.praise_text = praise_text
        else:
            report = WeeklyReport(
                user_id=user_id,
                week_index=week_index,
                kpis_json=json.dumps(kpis),
                praise_text=praise_text
            )
            db.session.add(report)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': {
                'report_id': report.id,
                'kpis': kpis,
                'praise_text': praise_text,
                'week_index': week_index,
                'generated_at': datetime.utcnow().isoformat()
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500

@analytics_bp.route('/learning-trends/<int:user_id>', methods=['GET'])
def get_learning_trends(user_id):
    """获取学习趋势分析"""
    try:
        days = request.args.get('days', 30, type=int)
        end_date = datetime.utcnow().date()
        start_date = end_date - timedelta(days=days-1)
        
        # 学习活跃度趋势
        activity_trend = []
        for i in range(0, days, 7):  # 按周统计
            week_start = start_date + timedelta(days=i)
            week_end = min(week_start + timedelta(days=6), end_date)
            
            week_sessions = db.session.query(func.count(Session.id)).filter(
                Session.user_id == user_id,
                Session.date >= week_start,
                Session.date <= week_end
            ).scalar() or 0
            
            week_time = db.session.query(func.sum(Session.duration_sec)).filter(
                Session.user_id == user_id,
                Session.date >= week_start,
                Session.date <= week_end
            ).scalar() or 0
            
            activity_trend.append({
                'week_start': week_start.isoformat(),
                'sessions': week_sessions,
                'total_time': week_time,
                'avg_session_time': (week_time / week_sessions) if week_sessions > 0 else 0
            })
        
        # 掌握度分析
        mastery_analysis = db.session.query(
            func.count(Mistake.id).label('total'),
            func.avg(Mistake.mastery_level).label('avg_mastery')
        ).filter(Mistake.user_id == user_id).first()
        
        return jsonify({
            'success': True,
            'data': {
                'activity_trend': activity_trend,
                'mastery_analysis': {
                    'total_mistakes': mastery_analysis.total or 0,
                    'average_mastery': round(mastery_analysis.avg_mastery or 0, 1)
                },
                'analysis_period': {
                    'start_date': start_date.isoformat(),
                    'end_date': end_date.isoformat(),
                    'days': days
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

